﻿using AutoMapper;
using PagedList;
using SIG.DAL.Dapper.Model;
using SIG.DAL.Dapper.Repositories;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Albums;
using SIG.Resources.Admin;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Albums;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class AlbumController : BaseController
    {
        private readonly AlbumRepository _albumService;

        private readonly PageMetaRepository _pageMetaService;
        private readonly IMapper _mapper;

        public AlbumController(IAlbumService albumService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _albumService = new AlbumRepository();
            _pageMetaService = new PageMetaRepository();
            _mapper = mapper;

        }
        // GET: Admin/Album

        #region Album

        public ActionResult Index(int? page, string keyword)
        {
            AlbumListVM albumListVM = GetElements(page, keyword);

            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(albumListVM);

            //List<AlbumVM> vm = GetAlbumList();
            //return View(vm);
        }

        private AlbumListVM GetElements(int? page, string keyword)
        {
            var albumListVM = new AlbumListVM()
            {
                Keyword = keyword,
                PageIndex = (page ?? 1),
                PageSize = SettingsManager.Album.PageSize
            };
            int totalCount;
            var list = _albumService.GetListPagedItems(albumListVM.PageIndex, albumListVM.PageSize, albumListVM.Keyword, out totalCount);
          //  var specialistVMList = _mapper.Map<List<Album>, List<AlbumVM>>(specialistlist);
            albumListVM.TotalCount = totalCount;
            albumListVM.Albums = new StaticPagedList<Album>(list, albumListVM.PageIndex, albumListVM.PageSize, albumListVM.TotalCount); ;
            return albumListVM;
        }

        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/AlbumSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        [HttpGet]
        public ActionResult Add()
        {
            var vAlbum = new AlbumIM()
            {
                Active = true
            };
            //vAlbum.Importance = 0;

            return PartialView("_Add", vAlbum);
        }



        [HttpPost]
        public JsonResult Add(AlbumIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newAlbum = _mapper.Map<AlbumIM, Album>(vm);
            newAlbum.CreatedBy = Site.CurrentUserName;
            newAlbum.CreatedDate = DateTime.Now;
            _albumService.Create(newAlbum);

         
            var pageMeta = new PageMeta()
            {
                ObjectId = newAlbum.Id.ToString(),
                Title = string.IsNullOrEmpty(vm.SEOTitle) ? vm.Title : vm.SEOTitle,
                Keyword = string.IsNullOrEmpty(vm.Keywords) ? vm.Title : vm.Keywords.Replace('，', ','),
                Description = vm.SEODescription,
                ModelType = (short)ModelType.ALBUM
            };
            _pageMetaService.Create(pageMeta);
           

            int count;
            var pageSize = SettingsManager.Album.PageSize;
            var list = _albumService.GetListPagedItems(1, pageSize, string.Empty, out count);
         //   List<AlbumVM> categories = _mapper.Map<List<Album>, List<AlbumVM>>(list);
            AR.Data = RenderPartialViewToString("_AlbumList", list);

            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Album));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            Album album = _albumService.GetById(id);
            if (album == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<AlbumIM>(album);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.ALBUM, album.Id.ToString());
            if (pageMeta != null)
            {
                vm.SEOTitle = pageMeta.Title;
                vm.Keywords = pageMeta.Keyword;
                vm.SEODescription = pageMeta.Description;
            }

            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(AlbumIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            var newAlbum = _albumService.GetById(vm.Id);
            newAlbum.Title = vm.Title;
            newAlbum.Active = vm.Active;
            newAlbum.Cover = vm.Cover;
            newAlbum.UpdatedBy = Site.CurrentUserName;
            newAlbum.UpdatedDate = DateTime.Now;
            //var newAlbum = _mapper.Map<AlbumIM, Album>(vm);

            _albumService.Update(newAlbum);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.ALBUM, vm.Id.ToString());
            pageMeta = pageMeta ?? new PageMeta();


         

                pageMeta.ObjectId = vm.Id.ToString();
            pageMeta.Title = string.IsNullOrEmpty(vm.SEOTitle) ? vm.Title : vm.SEOTitle;
            pageMeta.Keyword = string.IsNullOrEmpty(vm.Keywords) ? vm.Title : vm.Keywords.Replace('，', ',');
            pageMeta.Description = vm.SEODescription;
                pageMeta.ModelType = (short)ModelType.ALBUM;

                if (pageMeta.Id > 0)
                {
                    _pageMetaService.Update(pageMeta);
                }
                else
                {
                    _pageMetaService.Create(pageMeta);
                }
            

           // var album = _mapper.Map<AlbumVM>(newAlbum);
            AR.Id = newAlbum.Id;
            AR.Data = RenderPartialViewToString("_AlbumItem", newAlbum);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Album));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Album vAlbum = _albumService.GetById(id);

            if (vAlbum.Photos.Any())
            {
                AR.Setfailure("此相册下面还有文章存在，不能删除！");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _albumService.Delete(vAlbum);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Album));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vAlbum = _albumService.GetById(id);
            if (vAlbum == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vAlbum.Active = !vAlbum.Active;
                _albumService.Update(vAlbum);

              //  var vm = _mapper.Map<AlbumVM>(vAlbum);

                AR.Data = RenderPartialViewToString("_AlbumItem", vAlbum);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Album));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        //[AllowAnonymous]
        //public JsonResult IsSeoNameUnique(string seoName, int? Id)
        //{
        //    return !IsExist(seoName, Id)
        //        ? Json(true, JsonRequestBehavior.AllowGet)
        //        : Json(false, JsonRequestBehavior.AllowGet);
        //}
        //[AllowAnonymous]
        //public bool IsExist(string seoName, int? id)
        //{
        //    var wType = _albumService.GetAll().Where(w => w.SeoName == seoName);
        //    if (id > 0)
        //    {
        //        wType = wType.Where(w => w.Id != id);
        //    }

        //    if (wType.Count() > 0)
        //        return true;

        //    return false;
        //}



        #endregion
    }
}